<template>
  <div class="delivery-way">
    <div class="sticky left-0 right-0 top-0 z-9 box-border h-full bg-hex-ffffff px-28rpx pb-32rpx">
      <div class="z-999 flex items-center justify-between" :style="{ paddingTop: `${searchBarTop}px` }" @click.stop="goback">
        <uni-icons type="back" size="28" />
        <span class="flex-1 text-36rpx" style="text-align: center;">配送方式</span>
      </div>
      <div class="mt-36rpx flex items-center justify-center">
        <div class="box-border h-64rpx w-392rpx flex items-center justify-between rounded-60rpx bg-hex-ABCD03 px-4rpx text-28rpx text-hex-fff">
          <div v-for="item in titleList" :key="item.id" class="h-56rpx w-192rpx rounded-56rpx text-center leading-56rpx"
               :class="{ 'text-hex-ABCD03 bg-hex-fff': location.selfPickup === item.id }" @click="toggleTab(item)">
            <div v-if="item">{{ item.name }}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 门店自提 -->
    <div v-if="location.selfPickup === 0">
      <!-- 输入框 -->
      <div class="flex justify-center">
        <div class="mt-20rpx h-68rpx w-686rpx flex items-center rounded-68rpx bg-hex-f5f5f5">
          <div class="relative w-full">
            <div class="absolute left-32rpx top-50% h-40rpx w-98rpx flex translate-y-(-50%) items-center">
              <div class="mr-20rpx text-32rpx">长沙</div>
              <div class="triangle" />
            </div>
            <div class="absolute left-144rpx top-50% h-20rpx w-2rpx translate-y-(-50%) bg-hex-D9D9D9FF" />
            <div class="relative left-180rpx">
              <input
                placeholder-class="text-hex-999 text-28rpx font-400" type="text" placeholder="请输入当前地址搜索附近门店">
            </div>
          </div>
        </div>
      </div>
      <!-- 地址列表 -->
      <div class="mt-12rpx">
        <div v-if="location.storeList.length > 0">
          <div v-for="item in location.storeList"
               class="flex justify-center">
            <div v-if="item.isOpen" class="w-686rpx flex justify-between border-2rpx border-transparent border-b-hex-f5f5f5 border-solid py-40rpx"
                 @click="selectStoreAddress(item)">
              <div>
                <div class="flex text-28rpx font-600 text-hex-333">
                  <div>{{ item.storeName }}</div>
                  <image
                    :src="`${cdnUrl}/svgicons/tea/leaf.svg${imgVersion}`"
                    mode="scaleToFill"
                    class="h-33rpx w-37rpx"
                  />
                </div>
                <div class="flex py-18rpx text-26rpx font-400 text-hex-7C8699">
                  <image
                    :src="`${cdnUrl}/svgicons/tea/position.svg${imgVersion}`"
                    mode="scaleToFill"
                    class="mr-6rpx h-40rpx w-40rpx"
                  />
                  <div class="h-28rpx w-484rpx w-full border-2rpx border-transparent border-r-hex-D9D9D9 border-solid text-26rpx">{{ item.storeAddressDetail }}</div>
                </div>
                <div class="flex text-26rpx font-400 text-hex-7C8699">
                  <image
                    :src="`${cdnUrl}/svgicons/tea/time.svg${imgVersion}`"
                    mode="scaleToFill"
                    class="mr-6rpx h-40rpx w-40rpx"
                  />
                  <div>{{ item.storeName }} {{ item.storeStartTime??'全天营业' }}-{{ item.storeEndTime??'' }}</div>
                </div>
                <div class="mt-24rpx text-24rpx text-hex-ABCD03" @click.stop="openLocation(item)">查看详细地址</div>
              </div>
              <div>
                <div class="h-full flex-col justify-between">
                  <div class="w-full flex justify-center justify-center">
                    <image
                      :src="`${cdnUrl}/svgicons/tabbar/tea_select.svg${imgVersion}`"
                      mode="scaleToFill"
                      class="mr-6rpx h-60rpx w-60rpx"
                    />
                  </div>
                  <div class="pb-8rpx pt-4rpx text-32rpx font-600 text-hex-ABCD03">去点单</div>
                  <div class="text-24rpx text-hex-7C8699">距您{{ formatDistance(item.distance) }}</div>
                </div>
              </div>
            </div>
            <div v-if="!item.isOpen" class="w-686rpx flex justify-between border-2rpx border-transparent border-b-hex-f5f5f5 border-solid py-40rpx">
              <div>
                <div class="flex text-28rpx font-600 text-hex-E0E0E0">
                  <div>{{ item.storeName }}</div>
                  <image
                    :src="`${cdnUrl}/svgicons/tea/leaf.svg${imgVersion}`"
                    mode="scaleToFill"
                    class="h-33rpx w-37rpx"
                  />
                  <div>已打烊</div>
                </div>
                <div class="flex py-18rpx text-26rpx font-400 text-hex-E0E0E0">
                  <image
                    :src="`${cdnUrl}/svgicons/tea/position.svg${imgVersion}`"
                    mode="scaleToFill"
                    class="mr-6rpx h-40rpx w-40rpx"
                  />
                  <div class="h-28rpx w-484rpx w-full border-2rpx border-transparent border-r-hex-E0E0E0 border-solid text-26rpx">{{ item.storeAddressDetail }}</div>
                </div>
                <div class="flex text-26rpx font-400 text-hex-E0E0E0">
                  <image
                    :src="`${cdnUrl}/svgicons/tea/time.svg${imgVersion}`"
                    mode="scaleToFill"
                    class="mr-6rpx h-40rpx w-40rpx"
                  />
                  <div>{{ item.storeName }} {{ item.storeStartTime??'全天营业' }}-{{ item.storeEndTime??'' }}</div>
                </div>
                <div class="mt-24rpx text-24rpx text-hex-E0E0E0">查看详细地址</div>
              </div>
              <div>
                <div class="h-full flex-col justify-between">
                  <div class="w-full flex justify-center justify-center">
                    <image
                      :src="`${cdnUrl}/svgicons/tea_select.svg${imgVersion}`"
                      mode="scaleToFill"
                      class="mr-6rpx h-60rpx w-60rpx"
                    />
                  </div>
                  <div class="pb-8rpx pt-4rpx text-32rpx font-600 text-hex-E0E0E0">去点单</div>
                  <div class="text-24rpx text-hex-E0E0E0">距您{{ formatDistance(item.distance) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <div
            class="mt-200rpx flex items-center justify-center">
            <div>
              <image
                class="h-364rpx w-364rpx"
                :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
                mode="scaleToFill"
              />
              <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 配送上门 -->
    <div v-if="location.selfPickup === 1" class="box-border pb-182rpx">
      <!-- 配送上门 -->
      <div class="mt-32rpx box-border px-32rpx">
        <!-- 输入框 -->
        <div class="mt-44rpx flex justify-center">
          <div class="mt-20rpx w-686rpx text-28rpx text-32rpx font-600 text-hex-333">
            可供选货地址
          </div>
        </div>
        <!-- 地址列表 -->
        <div class="mt-12rpx pb-182rpx">
          <uni-swipe-action v-if="location.listData.length > 0">
            <uni-swipe-action-item
              v-for="(item, index) in location.listData"
              :key="index"
              :right-options="options2"
              @click="swipeClick($event, index, item)"
            >
              <view class="content-box" @click="() => {
                location.getRecentlyStore(item.lat, item.lon)
                location.updateSelectData(item)
                goUpDateAddress(item)
              }">
                <div class="flex justify-center">
                  <div class="w-686rpx flex justify-between border-2rpx border-transparent border-b-hex-f5f5f5 border-solid py-40rpx">
                    <div>
                      <div class="flex text-28rpx text-hex-333">
                        <div class="flex">
                          <div v-if="item.isDefault===1" class="mr-12rpx flex items-center rounded-6rpx bg-hex-ABCD03 px-10rpx py-4rpx text-center text-24rpx text-hex-fff">
                            默认</div>
                          <div class="mr-12rpx flex items-center border-1rpx border-hex-ABCD03 rounded-6rpx border-solid bg-hex-EDFDF8 px-9rpx py-3rpx text-center text-24rpx text-hex-ABCD03">
                            {{ item.alias }}</div>
                          <div class="mr-12rpx text-hex-7C8699">{{ item.address }}</div>
                        </div>
                      </div>
                      <div class="w-600rpx flex justify-between py-22rpx text-26rpx font-400 text-hex-333">
                        <div>{{ item.detail }}</div>
                        <div class="h-32rpx w-2rpx bg-hex-DDE2E0" />
                      </div>
                      <div class="flex border-2rpx border-transparent text-26rpx font-400 text-hex-333">
                        <div v-if="item">{{ item.name }}({{ item.gender===0?'女士':'先生' }})<text class="ml-24rpx">{{ item.mobile }}</text></div>
                      </div>
                    </div>
                    <div class="flex items-center" @click.stop="edit(item)">
                      <image
                        :src="`${cdnUrl}/svgicons/tea/edit.svg${imgVersion}`"
                        mode="scaleToFill"
                        class="h-40rpx w-40rpx"
                      />
                    </div>
                  </div>
                </div>
              </view>
            </uni-swipe-action-item>
          </uni-swipe-action>
          <div v-else>
            <div
              class="mt-200rpx flex items-center justify-center">
              <div>
                <image
                  class="h-364rpx w-364rpx"
                  :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
                  mode="scaleToFill"
                />
                <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
              </div>
            </div>
          </div>
        </div>
        <div
          class="fixed bottom-0 left-32rpx right-32rpx h-182rpx flex items-center justify-center bg-[rgba(255,255,255)]"
          @click="navTo('/pages-tea/addAddress')">
          <div class="h-76rpx w-100% border-2rpx border-hex-ABCD03 rounded-12rpx border-solid text-center text-28rpx leading-76rpx text-hex-ABCD03">添加地址</div>
        </div>
      </div>
    </div>
    <!-- 删除弹窗 -->
    <confirm ref="delpop" />
  </div>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/stores/user'
import { useAddressStore } from '@/stores/address'

const { user } = useUserStore()
let location: any = useAddressStore()
let searchBarTop: any = $ref('24')

onLoad(() => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
  uni.getSetting({
    success: (res) => {
      // 如果用户已经授权定位权限
      if (!res.authSetting['scope.userLocation']) {
        uni.showModal({
          title: '授权提示',
          content: '需要获取您的位置信息，请点击下方按钮进入设置页面进行授权',
          confirmText: '去设置',
          success(res) {
            if (res.confirm) {
              uni.openSetting({
                success(res) {
                  if (res.authSetting['scope.userLocation']) {
                    location.updateEmpower(true)
                    location.getPosition({})
                  }
                },
                fail(err) {
                  console.log(err)
                },
              })
            }
          },
        })
      }
    },
  })
})

const titleList = [
  { id: 0, name: '门店自提' },
  { id: 1, name: '配送上门' },
]
//编辑地址
const edit = (item) => navTo(`/pages-tea/addAddress?edit=1&id=${item.id}`)
let options2: any = $ref([{
  text: '取消',
  style: {
    backgroundColor: '#007aff',
  },
},
{
  text: '删除',
  style: {
    backgroundColor: '#F56C6C',
  },
},
])
//打开地图
const openLocation = (item) => {
  uni.openLocation({
    name: item.storeName || '地理位置',
    address: item.storeAddressDetail || '',
    scale: 18,
    longitude: item.longitude,
    latitude: item.latitude,
    provider: 'amap',
  })
}

// 删除弹窗
const delpop: any = $ref('')
const swipeClick = (e, index, item) => {
  let {
    content,
  } = e
  if (content.text === '删除') {
    delpop.showConfirm('确定删除这条地址吗?').then((res) => {
      if (res) {
        location.delListData(user.id, item.id)
      }
    })
  }
}
const toggleTab = (item) => {
  location.updateSelfPickup(item.id)
}

const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
  uni.$emit('wakeEvent')
  uni.$emit('handelEvent')
}

// 外送切换配送方式
const changeOutwakeMethod = async (item) => {
  // 切换取餐方式调用接口
  const reqData = {
    method: 'post',
    data: {
      'deliveryMethod': 1,
      'trolleyType': 2,
      'userAddressId': item.id,
    },
    headers: { UserId: user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/trolley/setTrolleyDeliveryMethod', reqData)
  if (status === 200 && data.code === 0) {
    goback()
  }
}
const goUpDateAddress = (item) => {
  changeOutwakeMethod(item)
  uni.$emit('updateAddress', item)
}
// 切换自提方式调用接口
const goUpdateOrderStoreDo = async (item) => {
  const reqData = {
    method: 'post',
    data: {
      'deliveryMethod': 2,
      'trolleyType': 2,
    },
    headers: { UserId: user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/trolley/setTrolleyDeliveryMethod', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    goback()
  }
}
const selectStoreAddress = (item) => {
  location.updateSelectStores(item)
  goUpdateOrderStoreDo(item)
}

let pageNo: any = $ref(1)
let TotalPage = $ref(0)
//下滑加载更多数据
const getMoreData = () => {
  if (TotalPage !== pageNo) {
    pageNo++
    if (location.selfPickup === 0) {
      location.getstoreList(pageNo, 10)
    } else {
      location.getListData(user.id, pageNo, 10)
    }
  }
}
watch(() => location.currentLocation, async () => {
  if (JSON.stringify(location.currentLocation) !== '{}') {
    location.getstoreList(pageNo, 10)
  }
}, { immediate: true })
watch(() => location.selfPickup, async () => {
  pageNo = 1
  if (location.selfPickup === 0) {
    location.getRecentlyStore(location.currentLocation.latitude, location.currentLocation.longitude)
    TotalPage = await location.getstoreList(pageNo, 10)
  } else {
    TotalPage = await location.getListData(user.id, pageNo, 10)
  }
})
onReachBottom(() => {
  getMoreData()
})
onMounted(async () => {
  if (location.selfPickup === 0) {
    TotalPage = await location.getstoreList(pageNo, 10)
  } else {
    TotalPage = await location.getListData(user.id, pageNo, 10)
  }

})


</script>

<style lang="scss">
.delivery-way{
  .triangle {
    width: 0;
    height: 0;
    border-left: 12rpx solid #000;
    border-top: 12rpx solid transparent;
    border-bottom:12rpx solid transparent;
  }
}
</style>
